<template>
  <view class="daily-job-detail">
    <PageHeader title="日结工作详情" :showBack="true" :onlyBack="false" />


    <!-- 职位头部信息 -->
    <view class="job-header bg-white p-[30rpx] mb-[20rpx]">
      <!-- 日结标签 -->
      <view class="daily-tag bg-red-50 text-red-600 px-[16rpx] py-[6rpx] rounded-[8rpx] text-[24rpx] inline-block mb-[16rpx]">
        日结工作
      </view>
      
      <!-- 职位标题 -->
      <text class="job-title text-[34rpx] font-bold mb-[16rpx] block">{{ jobInfo?.position_name }}</text>
      
      <!-- 薪资信息（突出显示） -->
      <text class="salary text-[36rpx] text-red-500 font-bold mb-[20rpx] block">
        {{ jobInfo?.salary }}元/天
      </text>
      <text class="info-item text-[26rpx] text-gray-600">公司名称：{{ jobInfo?.corporate_name }}</text>

      <view class="flex items-center my-[24rpx]">
        <text class="text-[24rpx] text-[#666] mr-[12rpx]">发布者：</text>
        <view class="flex items-center">
          <image 
            :src="jobInfo?.avatar_url || defaultAvatar" 
            class="w-[54rpx] h-[54rpx] rounded-full mr-[8rpx]" 
            mode="aspectFill" 
            @error="handleAvatarError" 
          />
          <text class="text-[24rpx] text-[#333]">{{ jobInfo?.name || '未知用户' }}</text>
        </view>
      </view>

      <!-- 基本信息行 -->
      <view class="basic-info flex flex-wrap gap-x-[40rpx] gap-y-[16rpx] mb-[24rpx]">
        <text class="info-item text-[26rpx] text-gray-600">{{ jobInfo?.location }}</text>
        <text class="info-item text-[26rpx] text-gray-600">{{ jobInfo?.experience }}</text>
        <text class="info-item text-[26rpx] text-gray-600">{{ jobTypeText }}</text>
        <!-- <text class="info-item text-[26rpx] text-gray-600">招{{ jobInfo?.number }}人</text> -->
      </view>
      
      <!-- 公司信息 -->
      <view class="company-info flex items-center">
<!--        <view class="company-logo w-[80rpx] h-[80rpx] bg-gray-100 rounded-[10rpx] flex items-center justify-center mr-[20rpx]">-->
<!--          <IconFont name="company" size="40rpx" class="text-gray-400" />-->
<!--        </view>-->
        <view class="company-details">
          <text class="company-name text-[30rpx] font-bold">{{ jobInfo?.corporateName }}</text>
          <!-- <text class="validity text-[24rpx] text-gray-500 mt-[8rpx] block">
            有效至 {{ jobInfo?.deadline }}
          </text> -->
        </view>
      </view>
    </view>

    <!-- 核心工作信息 -->
    <view class="job-core-info bg-white p-[30rpx] mb-[20rpx]">
      <text class="section-title text-[30rpx] font-bold mb-[20rpx] block pb-[10rpx] border-b border-gray-100">
        工作信息
      </text>
      
      <view class="info-list">
        <view class="info-item flex mb-[24rpx]">
          <view class="info-label w-[160rpx] text-[26rpx] text-gray-500">工作时长</view>
          <view class="info-content flex-1 text-[26rpx] text-gray-800">{{ calculateDays(jobInfo?.start_date, jobInfo?.end_date) }}天</view>
        </view>
        
        <view class="info-item flex mb-[24rpx]">
          <view class="info-label w-[160rpx] text-[26rpx] text-gray-500">结算方式</view>
          <view class="info-content flex-1 text-[26rpx] text-gray-800">日结</view>
        </view>
        
        <view class="info-item flex mb-[24rpx]">
          <view class="info-label w-[160rpx] text-[26rpx] text-gray-500">招聘人数</view>
          <view class="info-content flex-1 text-[26rpx] text-gray-800">{{ jobInfo.number }}人</view>
        </view>
        
        <view class="info-item flex">
          <view class="info-label w-[160rpx] text-[26rpx] text-gray-500">招聘时间</view>
          <view class="info-content flex-1 text-[26rpx] text-gray-800">{{ jobInfo?.start_date }} 至 {{ jobInfo?.end_date }}</view>
        </view>
      </view>
    </view>

    <!-- 职位详情 -->
    <view class="job-description bg-white p-[30rpx] mb-[20rpx]">
      <text class="section-title text-[30rpx] font-bold mb-[20rpx] block pb-[10rpx] border-b border-gray-100">
        工作描述
      </text>
      <view class="description-content text-[26rpx] text-gray-700 leading-[1.8]">
        <text v-for="(paragraph, index) in jobInfo.description?.split('\n')" :key="index">
          {{ paragraph }}
          <view class="h-[20rpx]"></view>
        </text>
      </view>
    </view>

    <!-- 联系方式 -->
    <view class="contact-info bg-white p-[30rpx] mb-[120rpx]">
      <text class="section-title text-[30rpx] font-bold mb-[20rpx] block pb-[10rpx] border-b border-gray-100">
        报名列表
      </text>
      <role v-if="tid" :tid="tid" :publisherId="jobInfo.member_id" :totalAmount="totalAmount" :isPublisher="isPublisher" @list="handleGetList" />

    </view>

    <!-- 状态和功能按钮 -->
    <view class="status-actions p-[30rpx] mb-[20rpx]" v-if="showActionButtons">
      
      <!-- 操作按钮区域 -->
      <view class="action-buttons flex flex-wrap gap-[20rpx]">
        <!-- 发布者操作按钮 -->
        <nut-button
          v-for="action in getPublisherActions(jobInfo.status || 0)"
          :key="action"
          size="small"
          @click="handlePublisherAction(action)"
          v-if="isPublisher"
          class="action-btn"
        >
          {{ action }}
        </nut-button>

        <!-- 执行者操作按钮 -->
        <nut-button
          v-for="action in getExecutorActions(jobInfo.status || 0)"
          :key="action"
          size="small"
          @click="handleExecutorAction(action)"
          v-if="isExecutor"
          class="action-btn"
        >
          {{ action }}
        </nut-button>
      </view>
    </view>


    <!-- 底部操作栏 -->
     <view v-if="jobInfo.releaseStatus == 5" class="bottom-bar fixed bottom-0 left-0 right-0 bg-white p-[20rpx] border-t border-gray-100 flex items-center gap-[20rpx]">
      <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" size="20" class="text-[#ff9900] mx-[10rpx]" />
      <text class="text-center text-[26rpx] text-gray-500 py-[20rpx]">
        已停止招聘，无法报名
      </text>
     </view>
    <view v-else class="bottom-bar fixed bottom-0 left-0 right-0 bg-white p-[20rpx] border-t border-gray-100 flex items-center gap-[20rpx]">
      <nut-button 
        class="flex-1"
        type="success"
        @click="showContactInfo"
      >
        <template #icon>
          <IconFont name="message" size="28rpx" class="mr-[10rpx]" />
        </template>
        在线咨询
      </nut-button>
      <nut-button 
        type="info"
        class="flex-1"
        @click="applyForJob"
        v-if="!hasSignUp"
      >
        立即报名
      </nut-button>
      <nut-button 
        class="flex-1"
        disabled
        v-else
      >
        已报名
      </nut-button>
    </view>
  </view>

  <!-- 修改金额弹窗 -->
  <nut-popup v-model:visible="showAmountDialog" position="center">
    <view class="amount-dialog bg-white rounded-xl p-[40rpx] w-[540rpx]">
      <view class="dialog-header text-center mb-[40rpx]">
        <text class="text-[36rpx] font-bold text-[#212529]">修改金额</text>
      </view>
      
      <view class="dialog-content">
        <view class="amount-info mb-[30rpx]">
          <text class="text-[28rpx] text-[#666666]">原金额：</text>
          <text class="text-[32rpx] font-bold text-[#f72585]">¥{{ currentAmount }}</text>
        </view>
        
        <view class="input-group mb-[30rpx]">
          <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">新金额：</text>
          <nut-input
            v-model="newAmount"
            type="digit"
            placeholder="请输入新金额"
            class="amount-input"
            :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
          />
          <text v-if="amountError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ amountError }}</text>
        </view>

        <view class="password-group mb-[40rpx]">
          <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">交易密码：</text>
          <nut-input
            v-model="amountPassword"
            type="password"
            placeholder="请输入6位交易密码"
            maxlength="6"
            class="password-input"
            :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
          />
          <text v-if="passwordError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ passwordError }}</text>
        </view>
      </view>
      
      <view class="dialog-actions flex gap-[20rpx]">
        <nut-button 
          type="default" 
          class="flex-1"
          @click="cancelAmountChange"
        >
          取消
        </nut-button>
        <nut-button 
          type="primary" 
          class="flex-1"
          @click="confirmAmountChange"
          :loading="isUpdatingAmount"
        >
          确定
        </nut-button>
      </view>
    </view>
  </nut-popup>

  <!-- 评价弹窗 -->
  <EvaluateModal :visible="evaluateModalVisible" :userInfo="currentEvaluateUser" @confirm="handleEvaluateConfirm"
    @cancel="handleEvaluateCancel" />

  <!-- 纠纷提示弹窗 -->
  <DisputeModal
    v-model:visible="showDisputeModal"
    :title="disputeModalConfig.title"
    :description="disputeModalConfig.description"
    :actions="disputeModalConfig.actions"
    :additional-info="disputeModalConfig.additionalInfo"
    :confirm-text="disputeModalConfig.confirmText"
    :loading="disputeModalLoading"
    @confirm="handleDisputeConfirm"
    @close="handleDisputeClose"
  />

  <!-- 客服联系弹窗 -->
  <CustomerServiceModal
    v-model:visible="showCustomerServiceModal"
    @close="handleCustomerServiceClose"
  />
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { showToast } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { get, post } from "@/utils/request";
import Taro from "@tarojs/taro";
import DisputeModal from "@/components/DisputeModal.vue";
import CustomerServiceModal from "@/components/CustomerServiceModal.vue";
import { StatusActions } from "@/constants/StatusActions";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import role from "./role.vue";
import defaultAvatar from "@/assets/pic/ren.png";

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const totalAmount = ref(0);
const hasSignUp = ref(false);
// 日结职位信息接口定义
interface DailyJobDetail {
  id: number;
  positionName?: string;
  type?: string;
  corporateName?: string;
  location?: string;
  experience?: string;
  salary?: string;
  timeFrame?: string;
  description?: string;
  number?: string;
  deadline?: string;
  contactPhone?: string;
  contactWechat?: string;
  status?: number;
  member_id?: string;
  name?: string;
  updateTime?: string;
  releaseStatus?: number;
  [property: string]: any;
}
// 下拉刷新

const calculateDays = (startDate, endDate) => {
  if (!startDate || !endDate) return 0;
  
  try {
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    // 计算时间差（毫秒）
    const timeDiff = end.getTime() - start.getTime();
    
    // 转换为天数（向上取整，包含开始和结束日期）
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
    
    return daysDiff > 0 ? daysDiff : 0;
  } catch (error) {
    console.error("日期计算错误:", error);
    return 0;
  }
};

const handleGetList = (list) => {
  console.log("list==>", list, userInfo.value.id);

  const rs = list.some(item => item.columns.member_id == userInfo.value.id);
  console.log("rs==>", rs);
  hasSignUp.value = !!rs;
}

// 职位类型数据（与发布页对应）
const jobTypes = ref([
  { text: '普工', value: '1' },
  { text: '技工', value: '2' },
  { text: '管理', value: '3' },
  { text: '质检', value: '4' },
  { text: '仓储', value: '5' },
  { text: '后勤', value: '6' },
  { text: '其他', value: '7' }
]);

// 职位详情数据
const jobInfo = ref<DailyJobDetail>({
  id: 0,
  status: 0, // 默认状态为待完成
});

// 用户身份判断
const isPublisher = ref(false);
const isExecutor = ref(false);

// 修改金额相关状态
const showAmountDialog = ref(false);
const newAmount = ref("");
const currentAmount = ref(0);
const amountError = ref("");
const isUpdatingAmount = ref(false);
const amountPassword = ref("");
const passwordError = ref("");

// 纠纷弹窗相关状态
const showDisputeModal = ref(false);
const disputeModalLoading = ref(false);
const disputeModalConfig = ref({
  title: '异议申请已提交',
  description: '我们已收到您的异议申请，平台将立即采取以下措施：',
  actions: [
    { icon: 'lock', text: '冻结当前阶段交易资金' },
    { icon: 'service', text: '客服将在24小时内联系双方' },
    { icon: 'clock', text: '纠纷处理期间暂停任务进度' }
  ],
  additionalInfo: '请准备好相关沟通记录作为证据，平台客服会通过注册手机号与您联系。',
  confirmText: '确认'
});

// 客服联系弹窗相关状态
const showCustomerServiceModal = ref(false);

// 评价弹窗相关状态
const evaluateModalVisible = ref(false);
const currentEvaluateUser = ref({});

// 计算属性：获取职位类型文本
const jobTypeText = computed(() => {
  const typeItem = jobTypes.value.find(item => item.value === jobInfo.value.type);
  return typeItem?.text || "其他";
});

// 计算属性：是否显示操作按钮
const showActionButtons = computed(() => {
  return isPublisher.value || isExecutor.value;
});

/**
 * 获取状态标签文字
 * @param status 任务状态码
 * @returns 状态标签文字
 */
const getStatusLabel = (status: number): string => {
  return StatusActions[status as keyof typeof StatusActions]?.label || "未知状态";
};

/**
 * 获取状态文字颜色
 * @param status 任务状态码
 * @returns CSS类名
 */
const getStatusTextColor = (status: number): string => {
  switch (status) {
    case 0:
      return "text-[#FF4D4F]"; // 待完成 - 红色
    case 3:
      return "text-[#52C41A]"; // 已完成 - 绿色
    case 21:
      return "text-[#FAAD14]"; // 待审核 - 橙色
    case 22:
      return "text-[#52C41A]"; // 确认完成 - 绿色
    case 23:
    case 24:
      return "text-[#FF4D4F]"; // 有纠纷/纠纷协商 - 红色
    default:
      return "text-[#666666]"; // 默认灰色
  }
};

/**
 * 获取状态点颜色
 * @param status 任务状态码
 * @returns CSS类名
 */
const getStatusDotColor = (status: number): string => {
  switch (status) {
    case 0:
      return "bg-[#FF4D4F]"; // 待完成 - 红色
    case 3:
      return "bg-[#52C41A]"; // 已完成 - 绿色
    case 21:
      return "bg-[#FAAD14]"; // 待审核 - 橙色
    case 22:
      return "bg-[#52C41A]"; // 确认完成 - 绿色
    case 23:
    case 24:
      return "bg-[#FF4D4F]"; // 有纠纷/纠纷协商 - 红色
    default:
      return "bg-[#666666]"; // 默认灰色
  }
};

/**
 * 获取发布者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getPublisherActions = (status: number): string[] => {
  return StatusActions[status as keyof typeof StatusActions]?.publisherActions || [];
};

/**
 * 获取执行者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getExecutorActions = (status: number): string[] => {
  return StatusActions[status as keyof typeof StatusActions]?.executorActions || [];
};

/**
 * 处理发布者操作
 * @param action 操作名称
 */
const handlePublisherAction = async (action: string) => {
  console.log("action==> 555", action, jobInfo);
  try {
    let newStatus = jobInfo.value.status || 0;
    
    // 根据操作名称确定新状态
    switch (action) {
      case "审核申请":
        // 显示报名申请列表，让发布者审核
        showSignUpList();
        return;
      case "确认完成":
        newStatus = 22;
        break;
      case "有纠纷":
        // 显示纠纷弹窗
        showDisputeModal.value = true;
        return;
      case "联系平台":
        // 显示客服联系弹窗
        showCustomerServiceModal.value = true;
        return;
      case "修改金额":
        // 修改金额操作，打开弹窗
        openAmountDialog();
        return;
      case "评价":
        // 跳转到评价页面
        Taro.navigateTo({
          url: `/pages-detail/post/recruit/evaluate?taskId=${jobInfo.value.id}&taskName=${jobInfo.value.position_name}&userName=${jobInfo.value.name}&userAvatar=${jobInfo.value.avatar_url || defaultAvatar}`
        });
        return;
      default:
        showToast({ title: "未知操作", icon: "error" });
        return;
    }

    // 调用接口更新状态
    const res = await post("/recruitmentDaily/updateStatus", {
      id: jobInfo.value.id,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      jobInfo.value.status = newStatus;
      
      showToast({ title: "操作成功", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("发布者操作失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  }
};

/**
 * 处理执行者操作
 * @param action 操作名称
 */
const handleExecutorAction = async (action: string) => {
  try {
    let newStatus = jobInfo.value.status || 0;
    
    // 根据操作名称确定新状态
    switch (action) {
      case "我已完成":
        newStatus = 21; // 待审核
        break;
      case "联系平台":
        // 显示客服联系弹窗
        showCustomerServiceModal.value = true;
        return;
      case "接受方案":
        const confirm = await Taro.showModal({
          title: "接受方案",
          content: "确定要接受方案吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!confirm.confirm) return;
        newStatus = 22; // 确认完成
        break;
      case "拒绝方案":
        const reject = await Taro.showModal({
          title: "拒绝方案",
          content: "确定要拒绝方案吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!reject.confirm) return;
        newStatus = 23; // 有纠纷
        break;
      default:
        showToast({ title: "未知操作", icon: "error" });
        return;
    }

    // 调用接口更新状态
    const res = await post("/recruitmentDaily/updateStatus", {
      id: jobInfo.value.id,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      jobInfo.value.status = newStatus;
      
      showToast({ title: "操作成功", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("执行者操作失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  }
};

/**
 * 打开修改金额弹窗
 */
const openAmountDialog = () => {
  currentAmount.value = parseFloat(jobInfo.value.salary || "0");
  newAmount.value = currentAmount.value.toString();
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
  showAmountDialog.value = true;
};

/**
 * 取消修改金额
 */
const cancelAmountChange = () => {
  showAmountDialog.value = false;
  newAmount.value = "";
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
};

/**
 * 确认修改金额
 */
const confirmAmountChange = async () => {
  // 验证金额输入
  const amount = parseFloat(newAmount.value);
  
  if (isNaN(amount) || amount <= 0) {
    amountError.value = "请输入有效的金额";
    return;
  }
  
  if (amount > currentAmount.value) {
    amountError.value = "新金额不能超过原金额";
    return;
  }

  // 验证密码输入
  if (!amountPassword.value || amountPassword.value.length !== 6) {
    passwordError.value = "请输入6位交易密码";
    return;
  }

  // 清除错误提示
  amountError.value = "";
  passwordError.value = "";
  
  try {
    isUpdatingAmount.value = true;
    
    // 调用接口修改金额
    const res = await post("/recruitmentDaily/updateAmount", {
      id: jobInfo.value.id,
      amount: amount,
      payPassword: amountPassword.value,
    });
    
    if (res.code === 0) {
      // 更新本地数据
      jobInfo.value.salary = amount.toString();
      
      showToast({ title: "金额修改成功", icon: "success" });
      
      // 关闭弹窗并清空数据
      showAmountDialog.value = false;
      newAmount.value = "";
      amountPassword.value = "";
    } else {
      // 根据错误类型显示不同提示
      if (res.message && res.message.includes('密码')) {
        passwordError.value = "交易密码错误";
      } else {
        showToast({ title: res.message || "金额修改失败", icon: "error" });
      }
    }
  } catch (error) {
    console.error("修改金额失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  } finally {
    isUpdatingAmount.value = false;
  }
};

/**
 * 处理纠纷弹窗确认
 */
const handleDisputeConfirm = async () => {
  disputeModalLoading.value = true;
  
  try {
    // 调用接口更新状态为有纠纷
    const res = await post("/recruitmentDaily/updateStatus", {
      id: jobInfo.value.id,
      status: 23,
    });

    if (res.code === 0) {
      // 更新本地状态
      jobInfo.value.status = 23;
      
      showDisputeModal.value = false;
      
      showToast({ title: "异议申请已提交", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("提交异议申请失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  } finally {
    disputeModalLoading.value = false;
  }
};

/**
 * 处理纠纷弹窗关闭
 */
const handleDisputeClose = () => {
  showDisputeModal.value = false;
};

/**
 * 处理客服联系弹窗关闭
 */
const handleCustomerServiceClose = () => {
  showCustomerServiceModal.value = false;
};
const tid = ref('')
// 页面加载时获取职位详情
const onLoad = async () => {
  // 获取页面参数中的职位ID
  const { id } = Taro.getCurrentInstance().router?.params || {};
  
  if (id) {
    tid.value = id
    try {
      Taro.showLoading({ title: "加载中..." });
      const res = await post('/recruitmentDaily/getById',{id});
      console.log('日结详情===>',res, userInfo.value)
      if (res.code === 0) {
        jobInfo.value = res.data.columns;
        console.log('jobInfo.value===>',jobInfo.value)
        // 判断用户身份
        isPublisher.value = jobInfo.value.member_id == userInfo.value.id;
        isExecutor.value = res.data.columns.members?.some((item: any) => 
          item.columns.member_id === userInfo.value.id?.toString() && item.columns.status === 11
        ) || false;
      } else {
        showToast({ title: "获取职位信息失败", icon: "none" });
      }

      // getRoles()
    } catch (error) {
      showToast({ title: "网络错误，请重试", icon: "none" });
    } finally {
      Taro.hideLoading();
    }
  }
};

const roles = ref([])
async function getRoles() {
  const { id } = Taro.getCurrentInstance().router?.params || {};
  const res = await post("/recruitmentDaily/signUpList",{recruitmentId: id})
  console.log("res==>",res)
  if(res.code == 0){
    roles.value = res.data.map(item => ({
      ...item.columns
    }))
    console.log("roles==>",roles.value)
  }
}

/**
 * 显示报名申请列表
 */
const showSignUpList = () => {
  // 获取报名申请列表
  getRoles();
  
  // 显示报名申请列表弹窗或跳转到报名列表页面
  Taro.navigateTo({
    url: `/pages-detail/post/recruit/role?tid=${jobInfo.value.id}&isPublisher=true`
  });
};

/**
 * 显示评价弹窗
 */
const showEvaluateModal = () => {
  currentEvaluateUser.value = {
    name: jobInfo.value.name || '用户',
    avatar: jobInfo.value.avatar_url || defaultAvatar,
    taskTitle: jobInfo.value.position_name || '任务',
  };
  evaluateModalVisible.value = true;
};

/**
 * 评价确认
 */
const handleEvaluateConfirm = async (evaluateData) => {
  console.log("评价数据：", evaluateData);

  // 显示完整的评价内容
  console.log("评分：", evaluateData.rating);
  console.log("完整评价内容：", evaluateData.comment);
  console.log("选择的标签：", evaluateData.tags);
  console.log("用户信息：", evaluateData.userInfo);

  try {
    // 这里可以调用API提交评价
    const res = await post("/task/score", {
      id: jobInfo.value.id,
      score: evaluateData.rating,
      reviewContent: evaluateData.evaluateData.comment,
      tags: evaluateData.tags,
    });

    if (res.code === 0) {
      showToast({ title: "评价提交成功", icon: "success" });
      // 更新任务状态为已评价
      jobInfo.value.status = 6; // 已评价状态
    } else {
      showToast({ title: res.message || "评价提交失败", icon: "error" });
    }
  } catch (error) {
    console.error("评价提交失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  } finally {
    evaluateModalVisible.value = false;
  }
};

/**
 * 评价取消
 */
const handleEvaluateCancel = () => {
  evaluateModalVisible.value = false;
};

// 初始化页面
onLoad();

// 下拉刷新处理
const onPullDownRefresh = async () => {
  const t = tid.value
  tid.value = ''
  await new Promise(r => setTimeout(r, 90));

  try {
    Taro.showLoading({ title: "刷新中..." });
    await onLoad(); // 重新获取数据
    showToast({ title: "刷新成功", icon: "success" });
  } catch (error) {
    console.error("下拉刷新失败:", error);
    showToast({ title: "刷新失败，请重试", icon: "none" });
  } finally {
    Taro.hideLoading();
    Taro.stopPullDownRefresh();
  }
  
  tid.value = t
};

// 注册下拉刷新
Taro.usePullDownRefresh(onPullDownRefresh);

Taro.useDidShow(async () => {
  tid.value = ''
  await new Promise(r => setTimeout(r, 90));
  onLoad();
});

// 返回上一页
const navigateBack = () => {
  navigateBack();
};

// 分享职位
const shareJob = () => {
  Taro.showToast({ title: "分享功能开发中", icon: "none" });
};

// 申请职位（报名）
const applyForJob = async () => {
  console.log("applyForJob ===>", userStore);
  const isReceive = await userStore.checkIsReceive();
  if(!isReceive) return;
  const { id } = Taro.getCurrentInstance().router?.params || {};
  const res = await post("/recruitmentDaily/signUp",{recruitmentId:id})
  if(res.code == 0){
    // 这里可以跳转到报名表单页面或直接提交申请
    showToast({ title: "报名已提交，请等待联系", icon: "none", duration:2000});
    setTimeout(() => {
      Taro.navigateBack();
    }, 1200);
  }
  else{
    showToast({ title: res.data, icon: "none", duration:2000});
  }
};

// 显示联系方式
const showContactInfo = () => {
  showToast({ title: "正在打开聊天窗口...", icon: "none" });
  console.log('===>',jobInfo.value.member_id),
  // 跳转聊天页面
  Taro.navigateTo({
    url:`/pages/message/chat?userId=${jobInfo.value.member_id}&userName=${jobInfo.value.name}`
  })
};

const handleAvatarError = (event) => {
  // 设置默认头像
  event.target.src = defaultAvatar;
};

</script>

<style>
.daily-job-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 导航栏样式 */
.navbar {
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn, .share-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 职位头部样式 */
.job-header {
  border-radius: 16rpx;
}

.daily-tag {
  background-color: #fff1f0;
  color: #dc2626;
}

.job-title {
  color: #333;
}

.salary {
  color: #dc2626; /* 日结工作薪资用更醒目的红色 */
}

/* 公司信息样式 */
.company-logo {
  background-color: #f0f0f0;
}

.company-name {
  color: #333;
}

/* 核心信息区块样式 */
.job-core-info .info-list {
  margin-top: 20rpx;
}

.info-label {
  color: #6b7280;
}

/* 详情区块样式 */
.section-title {
  color: #333;
  position: relative;
}

.section-title::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 60rpx;
  height: 4rpx;
  background-color: #dc2626; /* 日结用红色主题 */
}

/* 底部操作栏 */
.bottom-bar {
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 状态和操作区域样式 */
.status-actions {
  border-radius: 16rpx;
}

.current-status {
  background-color: #f8f9fa;
  border: 1rpx solid #e9ecef;
}

.status-dot {
  min-width: 12rpx;
  min-height: 12rpx;
}

.action-buttons {
  justify-content: flex-start;
}

.action-btn {
  min-width: 120rpx;
}
.nut-popup{
  border-radius: 20rpx;
}
</style>